﻿using Approval.API.Applcation.Command.PayRelationCommand;
using Approval.Domain;
using Approval.Infrastructure.Impl;
using Approval.Infrastructure.Interface;
using MediatR;

namespace Approval.API.Applcation.CommandHandler.PayRelationCommandHandler
{
    public class PayRelationCreateCommandHandler : IRequestHandler<PayRelationCreateCommand, int>
    {
        private readonly IPayRelationRepository payRelationRepository;

        public PayRelationCreateCommandHandler(IPayRelationRepository payRelationRepository)
        {
            this.payRelationRepository = payRelationRepository;
        }

        public async Task<int> Handle(PayRelationCreateCommand request, CancellationToken cancellationToken)
        {
            var list = await payRelationRepository.GetInfo(x => x.PayId == request.PayId && x.ApprovalState == 3);
            if (list != null)
            {
                await payRelationRepository.Delete(list.Id);
            }
            //默认第一次提交付款食品是彭于晏
            var payRelation = new PayRelation()
            {
                PayId = request.PayId,
                ApprovalId = request.ApprovalId!=0? request.ApprovalId :4,
                ApprovalName = (request.ApprovalName=="")?request.ApprovalName:"彭于晏",
                ApprovalDesc = null
            };
            var res = await payRelationRepository.Create(payRelation);
            return res;
        }
    }
}
